﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;

class Pool
{
    Transform m_parent;
    GameObject prefab;
    List<GameObject> roles = new List<GameObject>();

    public string Name { get { return prefab.name; } }

    public Pool(Transform parent,GameObject prefab)
    {
        this.m_parent = parent;
        this.prefab = prefab;
    }

    public GameObject Spawn()
    {
        GameObject go = null;
        foreach(var role in roles)
        {
            if(!role.activeSelf)
            {
                go = role;
                break;
            }
        }
        if(go==null)
        {
            go = GameObject.Instantiate<GameObject>(prefab);
            go.transform.parent = m_parent;
            roles.Add(go);
        }
        go.SetActive(true);
        ExecuteEvents.Execute<IRuseable>(go, null, (x, y) => x.Onspawn());
        return go;
    }
    public void Unspawn(GameObject go)
    {
        if(roles.Contains(go))
        {
            ExecuteEvents.Execute<IRuseable>(go, null, (x, y) => x.OnUnspawn());
            go.SetActive(false);
        }
    }
    public void UnspawnAll()
    {
        foreach(var m in roles)
        {
            if(m.activeSelf)
            {
                ExecuteEvents.Execute<IRuseable>(m, null, (x, y) => x.OnUnspawn());
                m.SetActive(false);
            }
        }
    }
    public bool Contain(GameObject go)
    {
        return roles.Contains(go);
    }
}
